<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use App\Model\Goods;
use DB,Validator;

class FavoriteController extends CommonController {

    public function index(Request $request) {
        if (!Session::has('userData')) {
            return response()->json(['status' => 0, 'info' => '请先登录']);
        }

        $data = [];
        $data['goods_id'] = $request->get('id');
        $data['user_id'] = Session ::get('userData')->id;
        $data['collect_time'] = date('Y-m-d H:i:s');
        $isfav = DB::table('user_collection')
                ->where('user_id', $data['user_id'])
                ->where('goods_id', $data['goods_id'])
                ->first();
        if ($isfav) {
            return response()->json(['status' => 0, 'info' => '已收藏']);
        }

        $res = DB::table('user_collection')->insert($data);

        if (false !== $res) {
            return response()->json(['status' => 1, 'info' => '收藏成功']);
        } else {
            return response()->json(['status' => 0, 'info' => '收藏失败']);
        }
    }
    
    // 获取列表
    public function getAllFavorite()
    {
        $user_id = Session::get('userData')->id;
        $favorites = DB::table('user_collection')->where('user_id', $user_id)
                ->paginate(20);
        
        foreach($favorites as $fav){
            $fav->goodsInfo = Goods::where('id', $fav->goods_id)
                    ->select(['goods_thumb','goods_name','goods_price','goods_num','goods_status'])
                    ->first();
        }
        return view('home.user.myfavorite', compact('favorites'));
    }
    
    // 删除收藏
    public function delete(Request $request)
    {
        $id = $request->get('id');
        $res = DB::table('user_collection')->where('id', $id)
                ->delete();
        if (false !== $res) {
            return response()->json(['status' => 1, 'info' => '删除成功']);
        } else {
            return response()->json(['status' => 0, 'info' => '删除失败']);
        }
    }
}
